<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * @name 		Main admin controller
 * @author 		Phil Sturgeon and Yorick Peterse - PyroCMS Development Team
 * @package 	PyroCMS
 * @subpackage 	Controllers
 */
class Admin extends Admin_Controller
{
	/**
	 * Constructor method
	 *
	 * @access public
	 * @return void
	 */
	public function __construct()
	{
		// Call the parent's controller
  		parent::Admin_Controller();
  		$this->load->model('users/user_m');
		// Set the validation rules
		$this->validation_rules = array(
			array(
				'field' => 'username',
				'label'	=> '管理員賬號',
				'rules' => 'required|callback__check_login'
			),
			array(
				'field' => 'password',
				'label'	=> '管理員密碼',
				'rules' => 'required'
			)
		);
		// Call validation and set rules
		$this->load->library('form_validation');
	    $this->form_validation->set_rules($this->validation_rules);
 	}
 	
	public function index()
	{
		$this->load->model('galleries/category_m');
		$categories = $this->category_m->get_many_by(array('parent_id' => 0));
		$this->template
			->set('categories', $categories)
			->build('galleries/admin/upload');
	}

	/**
	 * Log in
	 *
	 * @access public
	 * @return void
	 */
	public function login()
	{
		// If the validation worked, or the user is already logged in
	    if ($this->form_validation->run())
	    {
	    	$this->session->set_userdata('is_login', TRUE);
	    	redirect('admin/galleries/upload');
		}
	    $this->template->set_layout(FALSE)->build('admin/login');
	}

	/**
	 * Logout
	 *
	 * @access public
	 * @return void
	 */
	public function logout()
	{
//		$this->load->language('users/user');
		$this->session->set_userdata('is_login', FALSE);
		$this->session->set_flashdata('success', '您已經成功登出');
		redirect('admin/login');
	}

	/**
	 * Callback From: login()
	 *
	 * @access public
	 * @param string $email The Email address to validate
	 * @return bool
	 */
	public function _check_login($username)
	{
		if ( ! $this->user_m->check_login($username, $this->input->post('password')))
   		{
	   		$this->session->set_flashdata('error', '賬號或密碼錯誤');
	    	redirect('admin/login');
	    }
		
	    return TRUE;
	}
}